import * as React from 'react';
import { Table, Space, Button, Modal, Form, Input, message } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { reqAddCategory, reqCategorys, reqGetCategoryById, reqRemoveCategory, reqUpdateCategory } from '../../axios';
import './CategoryList.less'
export interface CategoryListProps {

}
export interface category {
    id: number
    icon: string
    name: string
    orderNum: number
}
export interface CategoryListState {
    categoryData: category[],
    isModalVisible: Boolean,
    isAdd: Boolean,
    getCategory : category
}

class CategoryList extends React.Component<CategoryListProps, CategoryListState> {
    formRef = React.createRef<FormInstance>();
    state = { 
        categoryData: [],
         isModalVisible: false,
         isAdd: true,
         getCategory: {
             id : 0,
             icon:'',
             name:'',
             orderNum:0
         }
    }
    async componentDidMount() {
        const response = await reqCategorys({});
        this.setState({ categoryData: response.data.data.records })
    }
    //modal确认
    handleOk = async () => {
        const {isAdd} = this.state;
        try {
            const values = await this.formRef.current?.validateFields();
            //添加分类
            if(isAdd){
                const response = await reqAddCategory(values);
                if (response.data.success) {
                    //因为没有返回id所以新增的分类 修改时会报错，因为修改时根据id查找的
                    this.setState((state) => {
                        return {
                            ...state,
                            isModalVisible: false,
                            categoryData: [...state.categoryData, response.data.data]
                        }
                    })
                    message.success(response.data.message);
                }else{
                    message.error(response.data.message);
                }
            }else{
                //修改分类
                const id = this.state.getCategory.id
                const newCategory = {...values,id}                
                const response = await reqUpdateCategory(newCategory);
                if (response.data.success) {
                    this.setState((state:CategoryListState) => {
                        return {
                            ...state,
                            isModalVisible: false,
                            categoryData: state.categoryData.map((category:category)=>{
                                if(category.id===id){
                                    return{
                                        ...newCategory
                                    }
                                }else{
                                    return{
                                        ...category
                                    }
                                }
                            }),
                            isAdd: state.isAdd,
                            getCategory: state.getCategory
                        }
                    })
                    message.success(response.data.message);
                }else{
                    message.error(response.data.message);
                }
            }
        } catch (error) {
            console.log(error);
        }
    };
    //modal取消
    handleCancel = () => {
        this.setState({ isModalVisible: false })
    };
    //删除分类
    removeCategory =async (id:number)=>{
       const response = await reqRemoveCategory(id);
       if(response.data.success){
           this.setState((state)=>{
               return{
                    categoryData:state.categoryData.filter(category=>category.id!==id)
               }
           })
           message.success(response.data.message);
       }
    }
    //更新分类
    updateCategory = async(id:number) =>{
       try {
        const response = await reqGetCategoryById(id);
        this.setState({isAdd:false,isModalVisible:true,getCategory:response.data.data})
       } catch (error) {
           console.log(error);
       }
    }

    render() {
        const { categoryData, isModalVisible,getCategory,isAdd } = this.state;
        const {name,icon,orderNum} = getCategory;
        const showModal = () => {
            this.setState({ isModalVisible: true,isAdd:true })
        };
        const columns = [
            {
                title: '分类名称',
                dataIndex: 'name',
                width: '25%'
            },
            {
                title: '分类图标',
                dataIndex: 'icon',
                width: '25%'
            },
            {
                title: '分类排序',
                dataIndex: 'orderNum',
                width: '25%'
            },
            {
                title: '操作',
                render: (text: any) => (
                    <Space size="middle">
                        <Button type='primary' onClick={()=>this.updateCategory(text.id)}>修改</Button>
                        <Button type='primary' danger onClick={()=>this.removeCategory(text.id)} >删除</Button>
                    </Space>
                ),
                width: '25%'
            },
        ];
        return (
            <div>
                <Button onClick={showModal} style={{ float: 'right', margin: '10px' }} type='primary'> 添加分类</Button>
                <Table columns={columns} rowKey='id' dataSource={categoryData} />
                <Modal destroyOnClose title={isAdd?"添加分类":"修改分类"} visible={isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form
                        ref={this.formRef}
                        name="basic"
                        //@ts-ignore
                        initialValues={isAdd?null:{name,icon,orderNum}}
                    >
                        <Form.Item
                            label="分类名称"
                            name="name"
                            rules={[{ required: true, message: '请输入分类的名称!' }]}

                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="分类图标"
                            name="icon"
                            rules={[{ required: true, message: '请输入分类的图标!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="分类排序"
                            name="orderNum"
                            rules={[{ required: true, message: '请输入分类的排序!' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default CategoryList;